import utils.TreeNode;

import java.util.Map;

/**
 * @author ZCR
 * @create 2025/8/16 20:31
 */
public class Solution105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);

    }

    public TreeNode buildTree(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
        if (inStart > inEnd) {
            return null;
        }
        if (inStart == inEnd) {
            return new TreeNode(inorder[inStart]);
        }
        TreeNode root = new TreeNode(preorder[preStart]);
        int leftLen = 0;
        int rightLen = 0;
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == preorder[preStart]) {
                leftLen = i - inStart;
                rightLen = inEnd - i;
                break;
            }
        }
        root.left = buildTree(preorder, inorder, preStart + 1, preStart + leftLen, inStart, inStart + leftLen - 1);
        root.right = buildTree(preorder, inorder, preEnd - rightLen + 1, preEnd, inEnd - rightLen + 1, inEnd);
        return root;
    }

    /**
     * labuladong的方法
     *
     * @param preorder
     * @param inorder
     * @param preStart
     * @param preEnd
     * @param inStart
     * @param inEnd
     * @return
     */
    public TreeNode buildTree2(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd, Map<Integer, Integer> inMap) {
        if (preStart > preEnd || inStart > inEnd) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[preStart]);
        int inRoot = inMap.get(root.val);
        int numsLeft = inRoot - inStart;
        root.left = buildTree2(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1, inMap);
        root.right = buildTree2(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd, inMap);
        return root;
    }

    public static void main(String[] args) {
        Solution105 solution = new Solution105();
        int[] preorder = {3, 9, 20, 15, 7}, inorder = {9, 3, 15, 20, 7};
        TreeNode root = solution.buildTree(preorder, inorder);
        TreeNode.show(root);
    }
}
